/**
 * @author philippdatz
 */

	var Beta = new Class({
	
		Implements: [Options, Events],
		
		options: {
			baseurl:	'',
			site: 		'',
			loader: 	$('loader'),
			info: 		$('info'),
		},
		
		tool:			'',
		
		initialize: function(options) {
			
			self = this;
			this.setOptions(options); 
			
			if ( Cookie.read('pages') == 1 ) {
				self.buildPageBox();
				$('pages').addClass('selected');
			}
			
			$('sidebar').addEvents({
				'mouseenter': function(){
					this.set('tween', {
						duration: 200,
						transition: Fx.Transitions.Quad.easeOut
					}).tween('top', '0px');
				},
				'mouseleave': function(){
					this.set('tween', {
						duration: 200,
						transition: Fx.Transitions.Quad.easeOut	
					}).tween('top', '-22px');
				}
			});
			
			$('drawer').addEvents({
			
				'mousedown': function(e) {
					
					if ( self.tool == 'add_box') {
					
						var length = $$('div.entry').length
						el = new Element('div', {
							'class': 'entry',
							'id': 'entry' + length,
							'styles': {
								'top': e.page.y.round(-1),
								'left': e.page.x.round(-1)
							}
						}).inject($('contents'));
						
						myResize = el.makeResizable({
							grid: 10,
							onComplete: function() {
								this.detach();
							}}).start(e);
					
					} else if ( self.tool == 'edit' ) {
						self.changeTool('use');
						self.saveSite();
					}
				},
				
				'mouseup': function(e) {
					if (self.tool == 'add_box') {
						self.buildEntry(el, "double-click to edit");
						el = '';
					}
				}
			});
			
			/* sidebar - functions */
		
			$('add_box').addEvent('click', function() {
				self.changeTool('use');
				self.tool = this.id;
				$$('div#sidebar a').removeClass('selected');
				this.addClass('selected');
				
				$('drawer').setStyle('cursor', 'crosshair');
			
			});
			
			// not implemented yet ...
			$('add_text').addEvent('click', function() {
				self.tool = this.id;
				$$('div#sidebar a').removeClass('selected');
				this.addClass('selected');
			
			});
			
			$('use').addEvent('click', function() {
				self.changeTool('use');
			});
			
			$('edit').addEvent('click', function() {
				self.changeTool('edit');
			});
			
			$('pages').addEvent('click', function() {
				
				self.tool = '';
				this.toggleClass('selected');
				
				if ( this.hasClass('selected')) {
					var pageCookie = Cookie.write('pages', 1);
					self.buildPageBox();
	
				} else {
					$('pages_container').destroy();
					var pageCookie = Cookie.write('pages', 0);
				}
			});
			
			$('save').addEvent('click', function() {
				self.saveSite();
			});
			
			// noch sehr schmutzig ...
			
			var x = new Chain();
			var un = this.loadSite('template');
			var dos = this.loadSite(this.options.site);
			x.chain(un);
			x.chain(dos);
			x.callChain();
			x.callChain();
		
		},
		
		loadSite : function(site) {
			
			if (site == 'template') {
				warning = 'Noch Kein Template angelegt.';
				var entryclass = 'entry_template';
			} else {
				warning = 'Diese Seite existiert noch nicht.';
				var entryclass = 'entry';
			}
			
			self = this;
			
			var loadReq = new Request.JSON({
				url: this.options.baseurl + 'loadpage',
				onComplete: function(jsonObj) {
					
					self.options.loader.setStyle('display', 'none');
					
					if (jsonObj) {
						
						existingEntries = $$('div.entry').length + $$('div.entry_template').length;
						
						jsonObj.entries.each(function(entry) {
							var el = new Element('div', {
								'class': entryclass,
								'id': 'entry' + existingEntries,
								'styles': {
									'top': entry.top,
									'left': entry.left,
									'height': entry.height,
									'width': entry.width
								}
							}).inject($('contents'));
							if (site !== 'template') {
								self.buildEntry(el, entry.content);
							} else {
								el.setStyle('z-index', -99999);
								
							}
							existingEntries++;
						});
						
					} else {
						self.options.info.set({
							'styles': {
							'display': 'block'
						},
							'html': warning
						});
					}
				}
				
			}).send('site=' + site);
			
		},
		
		buildEntry : function( entry, content ) {
		
			self = this;
			
			// use-mode
			var contentHolder = new Element('div', {
				'class':	'holder',
				'name':		entry.id + '_holder',
				'id':		entry.id + '_holder',
				'html':		content,
				'events':	{
					'dblclick': function() {
						self.changeTool('edit');
					},
					'mouseover': function() {
						var entries = $$('div.entry');
						entries.setStyle('z-index', 0);
						entry.setStyle('z-index', entries.length + 1);
					}
				}
				
			}).inject(entry);
			
			this.resizeContentHolder(entry, contentHolder);
			
			var deleter = new Element('a', {
				'class': 'delete',
				'html': 'x',
				'events': {
					'click': function() {
						this.getParent().destroy();
					}
				}
			}).inject(entry);
			
			var resizer = new Element('div', {
				'class': 'resizer'
			}).inject(entry);
			
			var myDrag = new Drag(entry, {
				grid: 10,
				onComplete: function(){
					self.saveSite();
				}
			});
			
			entry.makeResizable({
				handle: entry.getElements('.resizer'),
				grid: 10,
				onBeforeStart: function() {
					myDrag.detach();
				},
				onComplete: function(){
					self.resizeContentHolder(entry, contentHolder);
					myDrag.attach();
					self.saveSite();
				}
			});
		},
		
		saveSite : function() {
			
			self = this;
			
			this.options.loader.setStyle('display', 'block');
			
			var entries = $$('div.entry');
			var data = '';
			var count = entries.length;
			
			if (entries.length > 0) {
			
				data += '{"entries":[';
				
				entries.each(function(item, index){
					
					if ( self.tool !== 'edit' ) {
						content = item.getElement('div').get('html').replace(/"/g, '\\"').clean();
					} else {
						content = tinyMCE.get(item.getElement('textarea').id).getContent().replace(/"/g, '\\"').clean();
					}
					
					data += '{';
					
						data += '"top": ' + item.getCoordinates()['top'] + ', ';
						data += '"left": ' + item.getCoordinates()['left'] + ', ';
						data += '"height": ' + item.getCoordinates()['height'].round(-1) + ', ';
						data += '"width": ' + item.getCoordinates()['width'].round(-1) + ', ';
						data += '"content": ' + '"' + content + '"';
					
					data += '}';
					if (index < (count -1 )) data += ', ';
				});
				
				data += ']}';
				
			} 
			
			var saveReq = new Request({
				url: self.options.baseurl + 'save',
				onComplete: function(){
					self.options.loader.setStyle('display', 'none');
				}
			}).send("site=" + self.options.site + "&data=" + data );
			
		},
		
		resizeContentHolder : function(entry, contentHolder) {
			contentHolder.setStyles({
				'width': entry.getStyle('width').toInt() - 25,
				'height': entry.getStyle('height').toInt() - 25
			});
		},
		
		buildPageBox : function() {
			
			self = this;
			
			var el = new Element('div', {
				'id': 'pages_container',
				'styles': {
					'top': '100px',
					'left': '100px'
				}
			}).inject($('body'));
			
			el.makeDraggable();
			
			var loadPagesReq = new Request.JSON({
				url: self.options.baseurl + 'loadpages',
				onComplete: function(jsonObj){
					
					if (jsonObj) {
					
						jsonObj.pages.each(function(page){
						
							var p = new Element('p').inject(el);
							
							var a = new Element('a', {
								'html': page,
								'href': self.options.baseurl + page
							}).inject(p);
							
							var del = new Element('a', {
								'html': 'x',
								'events': {
									'click': function(){
										var check = confirm("Wollen Sie diese Seite wirklich loeschen?");
										if (check == true) {
											var deletePagesReq = new Request({
												url: self.options.baseurl + 'deletepage',
												onSuccess: function(){
													p.destroy();
												}
											}).send('site=' + page);
										}
									}
								}
							}).inject(p);
						});
					}
				}
			}).send();
		},
		
		changeTool : function( tool ) {
			
			switch ( tool ) {
				case 'use':
					if ( self.tool == 'edit' ) {
						$$('div.entry').each( function(entry) {
							
							var holder = 	entry.getElement('textarea');
							var content = 	tinyMCE.get(holder.id).getContent();
							
							tinyMCE.execCommand('mceRemoveControl', false, holder.id);
							var contentHolder = new Element('div', {
								'class':	'holder',
								'name':		entry.id + '_holder',
								'id':		entry.id + '_holder',
								'html':		content,
								'events':	{
									'dblclick': function() {
										self.changeTool('edit');
									},
									'mouseover': function() {
										var entries = $$('div.entry');
										entries.setStyle('z-index', 0);
										entry.setStyle('z-index', entries.length + 1);
									}
								}
							}).wraps(holder);
							self.resizeContentHolder(entry, contentHolder);
							holder.destroy();
							
						});
					}
					break;
					
				case 'edit':
					if (self.tool !== 'edit') {
						$$('div.entry').each(function(entry){
						
							var holder = entry.getElement('div');
							var contentHolder = new Element('textarea', {
								'class': 'holder',
								'name': entry.id + '_holder',
								'id': entry.id + '_holder',
								'html': holder.get('html')
							}).wraps(holder);
							
							self.resizeContentHolder(entry, contentHolder);
							holder.destroy();
							
						});
						mceSetup();
					}
					break;
			}
			
			$$('div#sidebar a').removeClass('selected');
			$(tool).addClass('selected');
			
			$('drawer').setStyle('cursor', 'default');
				
			self.tool = tool;
			
		}
		
	});